package com.firefly.admin.common.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.StringPool;
import com.firefly.admin.common.enums.ResultCodeEnum;
import com.firefly.admin.common.enums.WhiteListTypeEnum;
import com.firefly.admin.common.service.CommonService;
import com.firefly.admin.common.utils.AreaAddressUtil;
import com.firefly.admin.common.utils.RedisUtil;
import com.firefly.admin.common.utils.WeatherUtil;
import com.firefly.admin.common.vo.ProvinceInfo;
import com.firefly.admin.common.vo.Result;
import com.firefly.admin.common.vo.Weather;
import com.firefly.admin.system.entity.FySystemWhiteList;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang3.StringUtils;
import com.firefly.admin.common.constant.Constants;
import com.firefly.admin.common.exception.BusinessException;
import com.firefly.admin.system.service.FySystemWhiteListService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ClassPathResource;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;

import javax.annotation.PostConstruct;
import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@Service
@Slf4j
public class CommonServiceImpl implements CommonService {

    @Autowired
    private FySystemWhiteListService fySystemWhiteListService;

    private List<ProvinceInfo> provinceInfoList = null;

    @Override
    public HttpServletRequest getRequest() {
        //获取RequestAttributes
        RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
        if (requestAttributes == null) {
            throw new BusinessException(ResultCodeEnum.REQUEST_PARAM_EXCEPTION.getMsg());
        }
        //从获取到的RequestAttributes中获取HttpServletRequest的信息
        HttpServletRequest request = (HttpServletRequest) requestAttributes.resolveReference(RequestAttributes.REFERENCE_REQUEST);
        if (request == null) {
            throw new BusinessException(ResultCodeEnum.REQUEST_PARAM_EXCEPTION.getMsg());
        }
        return request;
    }

    /**
     * 获取天气信息接口
     *
     * @return 天气信息
     */
    @Override
    public Result<Weather> getWeather() {
        HttpServletRequest request = getRequest();
        if (request == null) {
            return Result.getResult(ResultCodeEnum.ERROR);
        }
        Weather weather = new Weather();
        try {
            //String localIp = IpUtil.getLocalIp(request);
            String localIp = "124.71.158.142";
            if (StringUtils.isNotBlank(localIp)) {
                String areaAddress = AreaAddressUtil.getAreaAddress(localIp);
                if (StringUtils.isNotBlank(areaAddress)) {
                    String[] areaArray = areaAddress.split("\\|");
                    String pro = areaArray[1].substring(0, areaArray[1].length() - 1);
                    String city = areaArray[2].substring(0, areaArray[2].length() - 1);
                    weather = WeatherUtil.getWeather(pro, city, city);
                }
            }
        } catch (Exception e) {
            log.error("CommonServiceImpl getWeather error!!,msg = {}", e.getMessage());
        }
        return Result.success(weather);
    }

    /**
     * 获取省份信息列表接口
     *
     * @return 省份信息列表
     */
    @Override
    public Result<List<ProvinceInfo>> getProvinceInfoList() {
        if (CollectionUtils.isEmpty(provinceInfoList)) {
            initProvinceData();
        }
        return Result.success(provinceInfoList);
    }

    @PostConstruct
    private void initProvinceData() {
        try {
            //读取省市区JSON文件
            ClassPathResource classPathResource = new ClassPathResource("META-INFO/resources/common/city.json");
            InputStream inputStream = classPathResource.getInputStream();
            File file = new File("META-INFO/resources/common/city.json");
            FileUtils.copyInputStreamToFile(inputStream, file);
            String jsonStr = FileUtils.readFileToString(file, StandardCharsets.UTF_8);
            provinceInfoList = JSONObject.parseArray(jsonStr, ProvinceInfo.class);
        } catch (Exception e) {
            log.error("#########initProvinceData error !! " + e.getMessage());
        }
    }

    @Override
    public boolean getSkipFilterAuthUrls(String requestUri) {
        List<String> skipSignAuthUrls = new ArrayList<>();
        Object redisValue = RedisUtil.hget(Constants.Redis.WHITE_LIST_KEY, WhiteListTypeEnum.SKIP_FILTER_AUTH.getWhiteListType());
        List<FySystemWhiteList> systemWhiteLists;
        if (redisValue == null) {
            systemWhiteLists = fySystemWhiteListService.getValueList(WhiteListTypeEnum.SKIP_FILTER_AUTH.getWhiteListType());
        } else {
            systemWhiteLists = (List<FySystemWhiteList>) redisValue;
        }
        if (!CollectionUtils.isEmpty(systemWhiteLists)) {
            skipSignAuthUrls = systemWhiteLists.stream().map(FySystemWhiteList::getWhiteListValue).collect(Collectors.toList());
        }
        if (CollectionUtils.isEmpty(skipSignAuthUrls)) {
            return false;
        }
        for (String url : skipSignAuthUrls) {
            if (url.equals(requestUri) || (url.endsWith(StringPool.ASTERISK) && requestUri.startsWith(url.substring(0, url.length() - 1)))) {
                return true;
            }
        }
        return false;
    }
}
